#include <iostream>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <strings.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include<string>
#include<functional>
using namespace std;
class Server
{
public:
    Server(uint16_t port)
        : _port(port)
    {
    }

    void Socket()
    {
        _listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensock < 0)
        {
            exit(-1);
        }
        cout<<"socket成功"<<endl;
    }
    void Bind()
    {
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = INADDR_ANY;
        local.sin_port = htons(_port);
        socklen_t len = sizeof(local);
        int ret = bind(_listensock, (struct sockaddr *)&local, len);
        if (ret < 0)
        {
            exit(-2);
        }
        cout<<"bind成功"<<endl;
    }

    void Listen()
    {
        int ret = listen(_listensock, backlog);
        if (ret < 0)
        {
            exit(-3);
        }
        cout<<"listen成功"<<endl;
    }

        static void* Routine(void* args)
        {
           Pthread_Data* data=static_cast<Pthread_Data*>(args);     
            data->cur->Service(data->sock,data->ip,data->port);
            delete data;
        }

    void Service(int sock,string ip,int port)
    {
        while(1)
        {
            char buff[1024];
            int n=read(sock,buff,sizeof(buff)-1);
            if(n>0)
            {
                buff[n]=0;
                cout<<"IP:"<<ip<<";"<<"Port:"<<port<<";data:"<<buff<<endl;
                write(sock,buff,n);;
            }
            else if(n==0)
            {
                cout<<"client已经关闭链接"<<endl;
                break;
            }
            else
            {
                exit(-4);
            }
        }
    }

    void Accept()
    {
        while (1)
        {
         
            Pthread_Data *ptr=new Pthread_Data;
            //cout<<2<<endl;
            struct sockaddr_in cli;
            socklen_t len = sizeof(cli);
            _sock = accept(_listensock, (struct sockaddr *)&cli, &len);
            cout<<"accept成功"<<endl;
            ptr->cur=this;
            ptr->ip=inet_ntoa(cli.sin_addr);
            ptr->port=ntohs(cli.sin_port);
            ptr->sock=_sock;
            pthread_t t;
            pthread_create(&t,nullptr,Routine,ptr);
        }
    }

private:
    class Pthread_Data
    {
    public:
        Server* cur;
        string ip;
        uint16_t port;
        int sock;
    };
    int _listensock;
    int _sock;
    uint16_t _port;
    const static int backlog = 32;
};
int main(int argc, char *argv[], char *envp[])
{
    if (argc != 2)
    {
        cout << "WAY:"
             << "\n\t"
             << "server port" << endl;
    }

    uint16_t port = atoi(argv[1]);
    Server s(port);
    s.Socket();
    s.Bind();
    s.Listen();
    s.Accept();
    return 0;
}